package org.vidyakiran.app.server.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.apache.commons.collections.Closure;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.vidyakiran.app.client.service.SuggestionService;
import org.vidyakiran.app.client.service.suggestion.ItemSuggestOracle;
import org.vidyakiran.app.client.service.suggestion.ItemSuggestion;

import com.google.gwt.user.client.ui.SuggestOracle.Request;
import com.google.gwt.user.client.ui.SuggestOracle.Response;
import com.google.gwt.user.client.ui.SuggestOracle.Suggestion;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class SuggestionServiceImpl extends RemoteServiceServlet implements
		SuggestionService {

	/**
	 * 
	 */
	private static final long serialVersionUID = -3798876436603388222L;

	@Override
	public Response getSuggestions(Request request) {
		String[] queryArray = request.getQuery().split(ItemSuggestOracle.DELIMITER);
		String suggestionType =queryArray[0];
		String query =queryArray[1];
		ReferenceDataServiceImpl refDataServiceImpl = new ReferenceDataServiceImpl();
		Object object = refDataServiceImpl.fetchReferenceDataByType(suggestionType);
		Response response = new Response();      
		
		if(object instanceof Collection<?>){
			Collection<String> rawCollection = (Collection<String>)object;
			Collection<Suggestion> suggestions = new ArrayList<Suggestion>();
			if(!StringUtils.isEmpty(query.trim())){
				suggestions = createSuggestions(filter(rawCollection,query)); 
			}else{
				suggestions = createSuggestions(rawCollection);
			}
			response.setSuggestions(suggestions);
		
		
		}
		
		
		return response;
	}

	private Collection<Suggestion> createSuggestions(Collection<String> c){
		Collection<Suggestion> suggestions = new ArrayList<Suggestion>();
		for(String s: c){
			suggestions.add(new ItemSuggestion(s));
		}
		return suggestions;
	}
	
	private Collection<String> filter(Collection<String> c,String query){
		Collection<String> filteredCollection = new ArrayList<String>();
		for(String string:c){
			if(string.toLowerCase().indexOf(query.toLowerCase())!=-1){
				filteredCollection.add(string);
			}
		}
		return filteredCollection;
	}
}
